/* ========================================================================
 * Tabs: jquery.tabs.js v1.0.0
 * http://getbootstrap.com/javascript/#buttons
 * ========================================================================
 * Copyright 2011-2016 Twitter, Inc.
 * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
 * ======================================================================== */

+function ($) {
    'use strict';
    let template = "<div class='content-tabs'>" +
                        "<button class='roll-nav roll-left tabLeft'>" +
                            "<i class='fa fa-backward'></i>" +
                        "</button>" +
                        "<nav class='page-tabs menuTabs'>" +
                            "<div class='page-tabs-content'>" +
                            "</div>" +
                        "</nav>" +
                        "<button class='roll-nav roll-right tabRight'>" +
                            "<i class='fa fa-forward'></i>" +
                        "</button>" +
                        "<div class='btn-group roll-nav roll-right'>" +
                            "<button class='dropdown J_tabClose' data-toggle='dropdown'>" +
                                   "页签操作<span class='caret'></span>" +
                            "</button>" +
                            "<ul role='menu' class='dropdown-menu dropdown-menu-right'>" +
                                "<li><a class='tabCloseCurrent' href='#'>关闭当前</a></li>" +
                                "<li><a class='tabCloseOther' href='#'>关闭其他</a></li>" +
                                "<li><a class='tabCloseAll' href='#'>全部关闭</a></li>" +
                            "</ul>" +
                        "</div>" +
                        "<a href='#' class='roll-nav roll-right tabReload'><i class='fa fa-refresh'></i> 刷新</a>" +
                    "</div>";


    // TABS PUBLIC CLASS DEFINITION
    // ==============================

    var Tabs = function (element, options) {
        this.$element = $(element);
        this.options = $.extend({}, Tabs.DEFAULTS, options);
        this.$element.html(template);

        //注册事件处理
        let tab = this;
        //选中Tab
        $('.menuTabs', this.$element).on('click', '.menuTab', function () {
            let fn = $.proxy(tab, "activeTab");
            fn(this);
        });
        //关闭Tab
        $('.menuTabs', this.$element).on('click', '.menuTab i', function (){
            let fn = $.proxy(tab, "closeTab");
            fn($(this).parent(".menuTab"));
        });
        //关闭其他选项卡
        $('.tabCloseOther', this.$element).on('click', $.proxy(tab, "closeOtherTabs"));
        //滚动到已激活的选项卡
        $('.tabShowActive', this.$element).on('click', $.proxy(tab, "showActiveTab"));

        // 刷新按钮
        $('.tabReload', this.$element).on('click', $.proxy(tab, "refreshTab"));
        $('.menuTabs', this.$element).on('dblclick', '.menuTab', $.proxy(tab, "refreshTab"));

        // 左移按扭
        $('.tabLeft', this.$element).on('click', $.proxy(tab, "scrollTabLeft"));

        // 右移按扭
        $('.tabRight', this.$element).on('click', $.proxy(tab, "scrollTabRight"));

        // 关闭当前
        $('.tabCloseCurrent', this.$element).on('click', $.proxy(function () {
            $('.page-tabs-content', this.$element).find('.active i').trigger("click");
        }, this));

        //关闭所有Tab
        $('.tabCloseAll', this.$element).on('click', $.proxy(tab, "closeAllTabs"));

        //加入首页
        this.createTab(this.options.indexPage.url, this.options.indexPage.title);
    }

    Tabs.VERSION = '1.0.0';

    Tabs.DEFAULTS = {
        indexPage: {url: '/index', title: '首页'},
        onTabCreated: function(id) { console.log("onTabCreated: id=" + id); },
        onTabActivated: function(id) { console.log("onTabActivated: id=" + id); },
        onTabClosed: function (id) { console.log("onTabClosed: id=" + id); },
        onRefreshTab: function (id) { console.log("onRefreshTab: id=" + id); }
    };


    //计算元素集合的总宽度
    function calSumWidth(elements) {
        var width = 0;
        $(elements).each(function() {
            width += $(this).outerWidth(true);
        });
        return width;
    }

    /**
     * 滚动到指定选项卡
     * dataUrl: 每个Tab对应一个dataUrl，用来记录用户Tab对应的链接Url
     */
    Tabs.prototype.scrollToTab = function (dataUrlOrElem) {
        let element = null;
        if (typeof dataUrlOrElem === "string") {
            //搜索对应dataUrl的DOM Element
            let menuTabs = $(".menuTab", this.$element).filter(function () {
                return $(this).data("id") === dataUrlOrElem;
            });
            if (menuTabs.length !== 0) {
                element = menuTabs[0];
            }
        } else if (typeof dataUrlOrElem === "object") {
            element = dataUrlOrElem;
        }
        if (element === null) { console.log("scrollToTab参数不正确"); return;}

        var marginLeftVal = calSumWidth($(element).prevAll()),
            marginRightVal = calSumWidth($(element).nextAll());
        // 可视区域非tab宽度
        var tabOuterWidth = calSumWidth($(".content-tabs", this.$element).children().not(".menuTabs"));
        //可视区域tab宽度
        var visibleWidth = $(".content-tabs", this.$element).outerWidth(true) - tabOuterWidth;
        //实际滚动宽度
        var scrollVal = 0;
        if ($(".page-tabs-content", this.$element).outerWidth() < visibleWidth) {
            scrollVal = 0;
        } else if (marginRightVal <= (visibleWidth - $(element).outerWidth(true) - $(element).next().outerWidth(true))) {
            if (marginRightVal < (visibleWidth - $(element).next().outerWidth(true))) {
                scrollVal = marginLeftVal;
                var tabElement = element;
                while ((scrollVal - $(tabElement).outerWidth()) > ($(".page-tabs-content", this.$element).outerWidth() - visibleWidth)) {
                    scrollVal -= $(tabElement).prev().outerWidth();
                    tabElement = $(tabElement).prev();
                }
            }
        } else if (marginLeftVal > (visibleWidth - $(element).outerWidth(true) - $(element).prev().outerWidth(true))) {
            scrollVal = marginLeftVal - $(element).prev().outerWidth(true);
        }
        $('.page-tabs-content', this.$element).animate({
                marginLeft: 0 - scrollVal + 'px'
            },
            "fast");
    }

    //查看左侧隐藏的选项卡
    Tabs.prototype.scrollTabLeft = function () {
        var marginLeftVal = Math.abs(parseInt($('.page-tabs-content', this.$element).css('margin-left')));
        // 可视区域非tab宽度
        var tabOuterWidth = calSumWidth($(".content-tabs", this.$element).children().not(".menuTabs"));
        //可视区域tab宽度
        var visibleWidth = $(".content-tabs", this.$element).outerWidth(true) - tabOuterWidth;
        //实际滚动宽度
        var scrollVal = 0;
        if ($(".page-tabs-content", this.$element).width() < visibleWidth) {
            return false;
        } else {
            var tabElement = $(".menuTab:first", this.$element);
            var offsetVal = 0;
            while ((offsetVal + $(tabElement).outerWidth(true)) <= marginLeftVal) { //找到离当前tab最近的元素
                offsetVal += $(tabElement).outerWidth(true);
                tabElement = $(tabElement).next();
            }
            offsetVal = 0;
            if (calSumWidth($(tabElement).prevAll()) > visibleWidth) {
                while ((offsetVal + $(tabElement).outerWidth(true)) < (visibleWidth) && tabElement.length > 0) {
                    offsetVal += $(tabElement).outerWidth(true);
                    tabElement = $(tabElement).prev();
                }
                scrollVal = calSumWidth($(tabElement).prevAll());
            }
        }
        $('.page-tabs-content', this.$element).animate({
                marginLeft: 0 - scrollVal + 'px'
            },
            "fast");
    }

    //查看右侧隐藏的选项卡
    Tabs.prototype.scrollTabRight = function () {
        var marginLeftVal = Math.abs(parseInt($('.page-tabs-content', this.$element).css('margin-left')));
        // 可视区域非tab宽度
        var tabOuterWidth = calSumWidth($(".content-tabs", this.$element).children().not(".menuTabs"));
        //可视区域tab宽度
        var visibleWidth = $(".content-tabs", this.$element).outerWidth(true) - tabOuterWidth;
        //实际滚动宽度
        var scrollVal = 0;
        if ($(".page-tabs-content", this.$element).width() < visibleWidth) {
            return false;
        } else {
            var tabElement = $(".menuTab:first", this.$element);
            var offsetVal = 0;
            while ((offsetVal + $(tabElement).outerWidth(true)) <= marginLeftVal) { //找到离当前tab最近的元素
                offsetVal += $(tabElement).outerWidth(true);
                tabElement = $(tabElement).next();
            }
            offsetVal = 0;
            while ((offsetVal + $(tabElement).outerWidth(true)) < (visibleWidth) && tabElement.length > 0) {
                offsetVal += $(tabElement).outerWidth(true);
                tabElement = $(tabElement).next();
            }
            scrollVal = calSumWidth($(tabElement).prevAll());
            if (scrollVal > 0) {
                $('.page-tabs-content', this.$element).animate({
                        marginLeft: 0 - scrollVal + 'px'
                    },
                    "fast");
            }
        }
    }

    //创建Tab
    Tabs.prototype.createTab = function (dataUrl, tabName) {
        let self = this;
        let isNew = true;   //Tab是否为新创建
        if (dataUrl == undefined || $.trim(dataUrl).length == 0) return false;

        // 选项卡菜单已存在
        $('.menuTab', this.$element).each(function() {
            if ($(this).data('id') == dataUrl) {
                if (!$(this).hasClass('active')) {
                    $(this).addClass('active').siblings('.menuTab').removeClass('active');
                    $('.page-tabs-content', this.$element).animate({ marginLeft: ""}, "fast");

                    // 滚动到可视位置
                    self.scrollToTab(this);

                    // 发出Tab被激活事件
                    self.options.onTabActivated(dataUrl);
                }

                isNew = false;
                return false;
            }
        });
        // 选项卡菜单不存在
        if (isNew) {
            var str = '<a href="javascript:;" class="active menuTab" data-id="' + dataUrl + '">' + tabName + ' <i class="fa fa-times-circle"></i></a>';
            $('.menuTab', this.$element).removeClass('active');

            // 添加选项卡对应的iframe
            this.options.onTabCreated(dataUrl);

            // 添加选项卡
            $('.menuTabs .page-tabs-content', this.$element).append(str);
            // 滚动
            self.scrollToTab($(".menuTab.active", this.$element));

            this.options.onTabActivated(dataUrl);

            //Tab为新建
            return true;
        }

        //表示Tab已存在，没有创建新Tab
        return false;
    }

    //关闭Tab
    Tabs.prototype.closeTab = function (tabElement) {
        let $tabElement = $(tabElement);
        var closeTabId = $tabElement.data('id');
        var currentWidth = $tabElement.width();

        // 当前元素处于活动状态
        if ($tabElement.hasClass('active')) {

            // 当前元素后面有同辈元素，使后面的一个元素处于活动状态
            if ($tabElement.next('.menuTab').length > 0) {

                var activeId = $tabElement.next('.menuTab:eq(0)').data('id');
                $tabElement.next('.menuTab:eq(0)').addClass('active');

                //发出Tab被激活事件-被关闭后面Tab自动激活
                this.options.onTabActivated(activeId);

                var marginLeftVal = parseInt($('.page-tabs-content').css('margin-left'));
                if (marginLeftVal < 0) {
                    $('.page-tabs-content').animate({
                            marginLeft: (marginLeftVal + currentWidth) + 'px'
                        },
                        "fast");
                }

                //  移除当前选项卡
                $tabElement.remove();

                //发出Tab关闭事件
                this.options.onTabClosed(closeTabId);
            }

            // 当前元素后面没有同辈元素，使当前元素的上一个元素处于活动状态
            if ($tabElement.prev('.menuTab').length > 0) {
                var activeId = $tabElement.prev('.menuTab:last').data('id');
                $tabElement.prev('.menuTab:last').addClass('active');
                //发出Tab被激活事件
                this.options.onTabActivated(activeId);

                //  移除当前选项卡
                $tabElement.remove();

                //发出Tab关闭事件
                this.options.onTabClosed(closeTabId);
            }
        }
        // 当前元素不处于活动状态
        else {
            //  移除当前选项卡
            $tabElement.remove();

            //发出Tab关闭事件
            this.options.onTabClosed(closeTabId);
            this.scrollToTab($('.menuTab.active'));
        }
        return false;
    }

    //关闭其他选项卡
    Tabs.prototype.closeOtherTabs = function (){
        let self = this;
        $('.page-tabs-content', this.$element).children("[data-id]").not(":first").not(".active").each(function() {
            self.options.onTabClosed($(this).data("id"));
            $(this).remove();
        });
        $('.page-tabs-content', this.$element).css("margin-left", "0");
    }

    //关闭全部Tab
    Tabs.prototype.closeAllTabs = function () {
        let self = this;
        $('.page-tabs-content', this.$element).children("[data-id]").not(":first").each(function() {
            self.options.onTabClosed($(this).data("id"));
            $(this).remove();
        });
        $('.page-tabs-content', this.$element).children("[data-id]:first").each(function() {
            $(this).addClass("active");
            self.options.onTabActivated($(this).data("id"));
        });
        $('.page-tabs-content', this.$element).css("margin-left", "0");
    }

    //滚动到已激活的选项卡
    Tabs.prototype.showActiveTab = function () {
        this.scrollToTab($('.menuTab.active', this.$element));
    }

    //点击选项卡菜单
    Tabs.prototype.activeTab = function (tabElem) {
        let $tab = $(tabElem);
        if (!$tab.hasClass('active')) {
            var currentId = $tab.data('id');
            // 触发激活Tab事件
            this.options.onTabActivated(currentId);
            $tab.addClass('active').siblings('.menuTab').removeClass('active');
            this.scrollToTab(this);
        }
    }

    //刷新Tab
    Tabs.prototype.refreshTab = function () {
        var currentId = $('.page-tabs-content', this.$element).find('.active').attr('data-id');
        this.options.onRefreshTab(currentId);
    }

    // TABS PLUGIN DEFINITION
    // ========================

    function Plugin(option) {
        var s = arguments;
        return this.each(function () {
            var $this   = $(this);
            var data    = $this.data('bs.tabs');
            var options = typeof option == 'object' && option;
            //构造Tabs实例
            if (!data) $this.data('bs.tabs', (data = new Tabs(this, options)));
            //功能调用
            if(typeof option === "string") {
                //取出option以后的参数作为函数调用的参数使用
                let args = Array.prototype.slice.call(s, 1);
                data[option].apply(data, args);
            }
        })
    }

    var old = $.fn.tabs;

    $.fn.tabs             = Plugin;
    $.fn.tabs.Constructor = Tabs;

    // TABS NO CONFLICT
    // ==================
    $.fn.tabs.noConflict = function () {
        $.fn.tabs = old;
        return this;
    }

    // TABS DATA-API
    // ===============

}(jQuery);